package com.agent;

import com.interceptor.RewriteAdvice;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.matcher.ElementMatchers;

import java.lang.instrument.Instrumentation;

public class T_03_RewriteAgent {

    /* 启动时生效 */
    public static void premain(String args, Instrumentation inst) {
        install(args, inst);
    }

    /* 运行时 attach 生效 */
    public static void agentmain(String args, Instrumentation inst) {
        install(args, inst);
    }

    private static void install(String args, Instrumentation inst) {
        new AgentBuilder.Default()
                // 1. 找到要改动的类
                .type(ElementMatchers.named("com.test.Aa"))
                // 2. 找到要改动的 method
                .transform((builder, td, cl, m) ->
                        builder.method(ElementMatchers.named("toString"))
                                .intercept(Advice.to(RewriteAdvice.class))
                )
                // 3. 对「已加载」的类也生效（热替换）
                .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
                .installOn(inst);
    }
}